import {  getUserInfo, getAccountInfo, getLoginStatus, loginOut } from '@/api/user'
import {  removeToken } from '@/utils/auth'

const state = {
  token: '',
  avatar: '',
  userid: '',
  account: '',
  profile: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERID: (state, id) => {
    state.userid = id
  },
  SET_AVATAR: (state, avatarUrl) => {
    state.avatar = avatarUrl
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_PROFILE: (state, profile) => {
    state.profile = profile
  }
}

const actions = {
  getLoginStatus({ commit }) {
    return new Promise((resolve, reject) => {
      getLoginStatus().then(response => {
        if (response.status == 200) {
          const { data: { data } } = response
          console.log('loginStatus:', data)
          if (data.account) {
            const { account, profile } = data
            const { avatarUrl } = profile
            const { id } = account
            commit('SET_USERID', id)
            commit('SET_AVATAR', avatarUrl)
            commit('SET_ACCOUNT', account)
            commit('SET_PROFILE', profile)
          }
          resolve(data)
        } else {
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token).then(response => {
        const { data } = response

        if (!data) { 
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_USERID', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get account info
  getAccountInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getAccountInfo(state.token).then(response => {
        const { data } = response
        commit('SET_USERID', 1)
        if (!data) { 
          reject('Verification failed, please Login again.')
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit,  dispatch }) {
    return new Promise((resolve, reject) => {
      // 这个退登接口成功后会重定向，如果成功之后再清空token数据可能会清空不了就刷新页面了，因此先清空token再发请求
      commit('SET_USERID', '')
      commit('SET_AVATAR', '')
      commit('SET_ACCOUNT', {})
      commit('SET_PROFILE', {})
      localStorage.removeItem('token')
      localStorage.removeItem('cookie')
      loginOut().then(() => {
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
